<?php

App::uses('AppController', 'Controller');

class CampaignsController extends AppController {
    
    public $pageTitle = "Kampanje";
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE,
        'group' => 'Campaign.id',
        'fields' => array(
            'Campaign.id', 'Campaign.name', 'Client.id', 'Client.name'
        ),
        'recursive' => false
    );
    
    public $uses = array('Campaign', 'Location', 'Client');
    
    public function index() {
        $filter = $this->parseFilterData('Campaign', array(
            'Campaign.start' => function($conditions, $value) {
                $conditions["Campaign.start <="] = $value;
                return $conditions;
            },
            'Campaign.end' => function($conditions, $value) {
                $conditions["Campaign.end >="] = $value;
                return $conditions;
            }
        ));
        
        $this->paginate['order'] = "{$filter->sortBy} {$filter->sortDir}";
        $campaigns = $this->paginate('Campaign', $filter->conditions);
        foreach ($campaigns as &$campaign) {
            $campaign['Location'] = $this->Campaign->locations($campaign['Campaign']['id']);
        }
        
        $this->set(compact('campaigns'));
        $this->setFilterData($filter);
    }
    
    private function setCommonData() {
        $clients = $this->Client->find('list');
        $locations = $this->Location->find('list');
        
        $this->set(compact('clients', 'locations'));
    }
    
    public function create() {
        $data = $this->Campaign->create();
        
        $clientId = (int)@$this->params->query['client'];
        if ($clientId) {
            $data['Client'] = Set::extract($this->Client->findById($clientId), 'Client');
        }
        
        $locationId = (int)@$this->params->query['location'];
        if ($locationId) {
            $data['CampaignsLocation'] = array(
                array(
                    'id'          => 0,
                    'location_id' => $locationId,
                    'production'  => '',
                    'mount'  => '',
                    'start'  => '',
                    'end'  => '',
                    'rabat'  => '',
                    'avans'  => ''
                )
            );
        }
        
        $dateStart = @$this->params->query['date'];
        if (! empty($dateStart)) {
            $data['Campaign']['start'] = $dateStart;
        }
        
        
        $this->set('data', $data);
        $this->setCommonData();
        $this->render('form');
    }
    
    public function edit($id) {
        $data = $this->Campaign->findById($id);
        $this->set('data', $data);
        $this->setCommonData();
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        
        if (! empty($data)) {
            $this->Campaign->create($data);
            $data2 = $data;
            if (! $this->Campaign->validates() || !$this->Campaign->validateAssociated($data2)) {
                $this->setCommonData();
                $this->set('data', $data);
                $this->setFlash('Uneti podaci nisu validni!');
                return $this->render('form');
            }
            
            $this->Campaign->deleteRelatedData();
            if (! $this->Campaign->saveAll($data)) {
                $this->setCommonData();
                $this->set('data', $data);
                $this->setFlash('Čuvanje nije uspelo!');
                return $this->render('form');
            }
            
            $this->setFlash('Kampanja je sačuvana.', 'ok');
            $this->redirect('edit/'.$this->Campaign->id);
        }
        
        $this->redirect('index');
    }
    
    public function remove($id) {
        if ($this->Campaign->delete($id)) {
            $this->setFlash('Kampanja je obrisana.', 'ok');
        } else {
            $this->setFlash('Greška pri brisanju kampanje.');
        }
        $this->redirect('index');
    }
    
    public function calendar() {
        $this->autoRender = false;
        
        $result = array();
        
        $days       = $this->params->query['days'];
        $locationId = $this->params->query['location'];
        foreach($days as $day) {
            $result[$day] = $this->Campaign->getByDateAndLocation($day, $locationId);
        }
        
        echo json_encode($result);
    }
    
    public function search() {
        $this->autoRender = false;
        
        $kword = $this->params->query['term'];
        $campaigns = array();
        $res = $this->Campaign->find('all', array(
            'fields'     => array('Campaign.id', 'Campaign.name', 'CampaignsLocation.*', 'Campaign.client_id'),
            'conditions' => array('OR' => array(
                'Campaign.name LIKE'  => "%{$kword}%",
                'CampaignsLocation.start LIKE' => "%{$kword}%",
                'Client.name LIKE'    => "%{$kword}%"
            )),
            'joins' => array(
                array(
                    'table'      => 'campaigns_locations',
                    'alias'      => 'CampaignsLocation',
                    'type'       => 'INNER',
                    'conditions' => array('CampaignsLocation.campaign_id = Campaign.id'),
                )
            ),
            'group' => 'Campaign.id'
        ));
        if ($res) {
            foreach ($res as $row) {
                $campaigns[] = array(
                    'id'    => $row['Campaign']['id'],
                    'label' => $row['Campaign']['label']
                );
            }
        }
        
        echo json_encode($campaigns);
    }

    public function data($id) {
        $this->autoRender = false;
        
        $data = $this->Campaign->find('first', array(
            'conditions' => array('Campaign.id' => $id),
            'recursive'  => 2
        ));
        echo json_encode($data);
    }
}
